<?php
/**
 * Created by PhpStorm.
 * User: linyida
 * Date: 2019/7/26
 * Time: 下午1:17
 */

namespace App\Storage;

use EasySwoole\Component\Singleton;
use EasySwoole\Component\TableManager;

class OnlineShop2 {

    use Singleton;
    protected $table;

    function __construct()
    {
        TableManager::getInstance()->add('OnlineShops',[
            'fd' => ['type' => Table::TYPE_INT, 'size' => 8],
            'shop_id' => ['type' => Table::TYPE_INT, 'size' => 8],
            'user_id' => ['type' => Table::TYPE_INT, 'size' => 8],
            'last_heartbeat' => ['type' => Table::TYPE_INT, 'size' => 4], //用户最后一次访问
        ]);

        $this->table = TableManager::getInstance()->get('OnlinShops');
    }

    /**
     * 设置一条用户信息。key 是客服id，value是用户信息
     * @param $fd
     * @param $shopId
     * @param $shopUserId
     * @return mixed
     */
    function set($fd, $shopId, $shopUserId) {
        return $this->table->set($shopUserId, [
            'fd'                => $fd,
            'shop_id'           => $shopId,
            'shop_user_id'       => $shopUserId,
            'last_heartbeat'    => time(),
        ]);
    }

    /**
     * 更新一条用户信息
     * @param $fd
     * @param $data
     */
    function update($shopUserId, $data) {
        $info = $this->get($shopUserId);
        if ($info) {
            $info = $data + $info;
            $this->table->set($shopUserId,$info);
        }
    }

    /**
     * 获取一条用户信息
     * @param $fd
     * @return array|mixed|null
     */
    function get($shopUserId) {
        $info = $this->table->get($shopUserId);
        return is_array($info) ? $info : null;
    }

    /**
     * 删除一条用户信息
     * @param $fd
     */
    function delete($shopUserId) {
        $info = $this->get($shopUserId);
        if ($info) {
            $this->table->del($shopUserId);
        }
    }

    /**
     * 心跳更新
     * @param $fd
     */
    function updateHeartbeat($shopUserId) {
        $this->update($shopUserId,[
            'last_heartbeat' => time()
        ]);
    }

    /**
     * 心跳检测
     * @param int $ttl
     */
    function heartbeatCheck($ttl = 60) {
        foreach ($this->table as $item) {
            $time = $item['time'];
            if (($time + $ttl) < $time ) {
                $this->delete($item['shop_user_id']);
            }
        }
    }

    /**
     * 返回当前table
     * @return Table|null
     */
    public function table() {
        return $this->table;
    }

    /**
     * 返回当前用户总数
     * @return mixed
     */
    public function count() {
        return $this->table->count();
    }
}